<?php
namespace app\api\controller;
use think\facade\Db;
class News extends Base{
    //列表数据
    public function list_data(){
        $param = input('');

        $search_type = $param['type'] ? ['type_id' => $param['type']]:[];//判断是否需要筛选 分类
        $search = $param['keyWord'] ? [['title', 'like', '%'.$param['keyWord'].'%']]:[];//判断是否需要筛选 关键词
        $search_sort = $param['sortField'] ? [$param['sortField'] => $param['sort']]:[];//排序
        $listData = Db::table('an_news')
        // ->fetchSql(true)//输出mysql语句
        ->page($param['page'],$param['limit'])
        ->order($search_sort)
        ->where($search)
        ->where($search_type)
        ->withoutField(['content'])
        ->select()
        ->toArray(); 
        $this->info['data'] = [
            'list' => $listData,
            'type' => Db::table('an_type')->where('type', 'news')->order('id', 'desc')->select()->toArray()
        ];
        $this->info['total'] = Db::table('an_news')->where($search_type)->where($search)->count();
        return json($this->info);
    }

    //获取需要编辑数据
    public function get_detail_a(){
        $param = input('');
        $details = Db::table('an_news')->where('id',$param['id'])->find();
        $this->info['data'] = [
            'details'=>$details,
            'type' => []
        ];
        return json($this->info);
    }

    //删除数据
    public function del_data_a(){
        $param = input('');
        foreach($param['ids'] as $v){
            Db::table('an_news')->where('id',$v)->delete();
        }
        $this->logData('删除文章，id为'.implode(",", $param['ids']));
        return json($this->info);
    }

    //新增数据
    public function saveData(){
        $param = input('');
        $data = [
            'up_time'=>time(),
            'title'=>$param['title'],
            'min_title'=>isset($param['min_title'])?$param['min_title']:'',
            'cover'=>isset($param['cover'])?$param['cover']:'',
            'content'=>$param['content'],
            'sort'=>isset($param['sort'])?$param['sort']:0,
            'keywords'=>isset($param['keywords'])?$param['keywords']:'',
            'description'=>isset($param['description'])?$param['description']:'',
            "a_show"=>$param['a_show'],
            "type_id"=>$param['type_id'],
            "abstract"=>isset($param['abstract'])?$param['abstract']:'',
        ];

        if(empty($param['id'])){
            $data['create_time'] = time();
            $this->info['msg']='新增资讯成功';
        }else{
            $data['id'] = $param['id'];
            $this->info['msg']='修改资讯成功';
        }
        $this->logData($this->info['msg'].'，名称：'.$param['title']);

        //save 自动判断是编辑更新数据 还是 插入新数据
        $this->info['data'] = Db::table('an_news')->save($data);
        return json($this->info);
    }  
}
